/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.async;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.Contacts.Photos;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;

import com.phonebooksharing.android.util.CloseableUtil;
import com.phonebooksharing.android.util.GalleryUtilities;

public class LoadAndroidPhotoTask extends AsyncTask<Object, Object, Void> {
    private Context context;
    private ListView lv;
    private boolean isListView;
    
    public LoadAndroidPhotoTask(ListView lv) {
        this(lv, lv.getContext(), true);
    }

    public LoadAndroidPhotoTask(ListView lv, Context cx, boolean isListView) {
        this.isListView = isListView;
        this.context = cx;
        this.lv = lv;
    }

    @Override
    public Void doInBackground(Object... params) {
        long id = (Long)params[0];
        
        final Uri photoUri = Uri.parse("content://contacts/people/" + id + "/photo");
        Cursor c = context.getContentResolver().query(photoUri, new String[] { Photos.DATA }, null, null, null);
        final byte[] data;
        try {
            if (c != null && c.moveToNext()) {
                data = c.getBlob(0);
            } else {
                //TODO: placeholder? already exists!!!
                data = null;
            }
        } finally {
            CloseableUtil.safeClose(c);
            c = null;
        }
        
        if(data != null) {
            Bitmap b = BitmapFactory.decodeByteArray(data, 0, data.length);
            final Bitmap bm;
//            if(isListView) {//if list view scale and frame
                bm = GalleryUtilities.scaleBitmap(b, 55, 55);
                b.recycle();
                b = null;
//            } else {//otherwise send photo as is
//                bm = b;
//            }
            publishProgress(params[0], bm, params[1], (params.length == 3 ? params[2] : null) );
        }
        
        return null;
    }
    
    @Override
    public void onProgressUpdate(Object... result) {
        super.onProgressUpdate(result);
        
        //common params
        final Long id = (Long)result[0];
        final Bitmap bitmap = (Bitmap)result[1];
        final View view;

        // skip if bitmap wasnt found
        if(bitmap == null) return;
        
        try {//try to avoid any possible weird error with the threads and listview
            GalleryUtilities.addToContactCache(id, bitmap);
            
            if(!isListView) {
                final ImageView iv = (ImageView)result[2];
                iv.removeCallbacks(null);
                iv.setImageBitmap(null);
                iv.setImageBitmap(bitmap);
                return;
            }
    
            final int lvPosition, groupPosition, childPosition;
            //normal listview
            if(lv instanceof ExpandableListView) {
    
                groupPosition = (Integer)result[2];
                childPosition = (Integer)result[3];
                
                final long packetPos = ExpandableListView.getPackedPositionForChild(groupPosition, childPosition);
                final ExpandableListView elv = (ExpandableListView)lv;
                
                //skip updating this item if outside of bounds
                if(elv.getFlatListPosition(packetPos) <  elv.getFirstVisiblePosition() || elv.getFlatListPosition(packetPos) > elv.getLastVisiblePosition()) return;
                
                // find actual position and update view
                int visible = elv.getFlatListPosition(packetPos) - elv.getFirstVisiblePosition();
                view = elv.getChildAt(visible + 1);//add 2 (list view header and group header)
                
            } else {
                lvPosition = (Integer)result[2];
              //skip updating this item if outside of bounds
                if(lvPosition < lv.getFirstVisiblePosition() || lvPosition > lv.getLastVisiblePosition()) return;
                
                // find actual position and update view
                int visible = lvPosition - lv.getFirstVisiblePosition();
                view = lv.getChildAt(visible);
            }
            
            final ImageView iv = (ImageView)view.findViewById(android.R.id.icon);
            iv.removeCallbacks(null);
            iv.setImageBitmap(null);
            iv.setImageBitmap(bitmap);
            
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}